﻿var OptionalValidationClientSideHide = false;
var TopScrollPossition = 0;
var CloseContractDetail = false;
var CurrentTabElement = null;
var PageNumber = 1;
var IsSearchView = false;
var OptionalIDGlobal = null;
var OptionalAutoComElem = null;
var OptionalAutoComElemVal = null;
var OptionalTimerId = null;
var AddCurrencyDropVal = 1;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("ManageOptionals") != -1) {
        $.validator.addMethod("ManageOptionalRequireds", $.validator.methods.required, Messages["ManageOptionalRequireds"]);
        $.validator.addMethod("ManageOptionalDate", $.validator.methods.datePicker, Messages["ManageOptionalDate"]);
        $.validator.addMethod("ManageOptionalMaxLength10", $.validator.methods.maxlength, Messages["ManageOptionalMaxLength10"]);
        $.validator.addMethod("ManageOptionalMaxLength250", $.validator.methods.maxlength, Messages["ManageOptionalMaxLength250"]);
        $.validator.addClassRules({
            Required: {
                ManageOptionalRequireds: true,
            },
            Date: {
                ManageOptionalDate: true,
            },
            MaxLength10: {
                ManageOptionalMaxLength10: 10,
            },
            MaxLength250: {
                ManageOptionalMaxLength250: 250,
            },
        });
        $('#LoadOptionalDetailsForm').validate();
        LoadOptionalGrid();
    }
});
$(document).on('change', '.OptionalDetailsElementChange', function () {
    if (!$('#OptionalDetailsSaveBtn').hasClass("disabled")) {
        $('#OptionalDetailsSaveBtn').addClass('BackColorRed');
    }
});
$(document).on('change', '.ChangedOptionalGridElements', function () {
    $('#OptionalGridSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.AddOptionalDetailElementChange', function () {
    if (!$('#AddOptionalDetailBtn').hasClass("disabled")) {
        $('#AddOptionalDetailBtn').addClass('BackColorRed');
    }
});
function ShowOptional(OptionalID)
{
    OptionalIDGlobal = OptionalID;
    if (OptionalID == 0)
        AddOptional(OptionalID);
    else
    {
        ShowOptionalDetails(OptionalID)
    }
}
function AddNewOptionalDetailsShow() {
    if ($('#OptionalDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('Are you sure you want to leave this page? You Have Not Saved Data', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#AddOptionalDetailsDiv").show();
                AddCurrencyDropVal = $("#SelectedCurrency option:selected").val();
                $("#OptionalSaveCloseAddNewOptionalDetailBtns").hide();
            }
        });
    }
    else {
        $("#AddOptionalDetailsDiv").show();
        AddCurrencyDropVal = $("#SelectedCurrency option:selected").val();
        $("#OptionalSaveCloseAddNewOptionalDetailBtns").hide();
    }
}
function AddNewOptionalDetailsClose() {
    $('#AddOptionalDetailBtn').removeClass('BackColorRed');
    $("#AddOptionalDetailsDiv").hide();
    $("#OptionalSaveCloseAddNewOptionalDetailBtns").show();
}
function ShowOptionalDetails(OptionalID) {

    $.ajax({
        url: urls["OptionalLoadOptionalDetails"],
        data: { 'OptionalID': OptionalID },
        type: 'GET',
        success: function (data) {
            $("#OptionalDetailsDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            ShowOptionalDetailPopUp("OptionalDetailsDiv");
            InitOptionalDetailsDataCalendars();
            InitOptionalDetailsDataCalendarsFromToDiv();
            BindOptionalDetailsCurrencyDropGridDrop();
            OptionalIDGlobal = $("#OptionalID").val();
        }
    });
}
function AddOptional(OptionalID) {

    $.ajax({
        url: urls["OptionalLoadOptionalDetails"],
        data: { 'OptionalID': OptionalID },
        type: 'GET',
        success: function (data) {
            $("#AddOptionalDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            ShowOptionalDetailPopUp("AddOptionalDiv");
            InitOptionalDetailsDataCalendars();
            InitOptionalDetailsDataCalendarsFromToDiv();
        }
    });
}
$(document).on('click', '#AddOptionalDetailBtn', function () {
    if ($('#OptionalDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('You Have Not Saved Payments Data. If you add new data you lose unsaved data', 'Warning!', function (retVal) {
            if (retVal == true) {
                AddOptionalDetail();
            }
        });
    }
    else {
        AddOptionalDetail();
    }
});
function isValidAddPaxFromToRange(AddPaxFrom,AddPaxTo) {
    var isvalid = true
    var PaxFromarr = [];
    var PaxToarr = [];
    $(".PaxFrom").each(function (index, elem) {
        var trparent = $(elem).parent();
        var tdparent = trparent.parent();
        var PaxTo = parseInt($(tdparent.find(".PaxTo")).val());
        var PaxFrom = parseInt(elem.value);
        PaxFromarr.push(PaxFrom);
        PaxToarr.push(PaxTo);
    });
    for (var index = 0 ; index < PaxFromarr.length ; ++index) {
        if ((AddPaxFrom <= PaxToarr[index]) && (AddPaxFrom >= PaxFromarr[index]) || (AddPaxTo <= PaxToarr[index]) && (AddPaxTo >= PaxFromarr[index])) {
            isvalid = false;
            break;
        }
    }
    return isvalid;
}
function AddOptionalDetail() {
    if (parseInt($("#PaxTo").val()) < parseInt($("#PaxFrom").val())) {
        jAlert("Pax to must be greater than pax from or equal:", "Error!");
    }
    else {
        if (isValidAddPaxFromToRange(parseInt($("#PaxFrom").val()), parseInt($("#PaxTo").val()))) {
            if ($('#LoadAddOptionalDetailsForm').valid()) {
                var OptionalDetailsViewModel = {
                    PaxFrom: $("#PaxFrom").val(),
                    PaxTo: $("#PaxTo").val(),
                    SelectedCurrency: AddCurrencyDropVal,
                    Price: $("#Price").val(),
                    BusIncluded: $("#BusIncluded").prop('checked'),
                    GuideIncluded: $("#GuideIncluded").prop('checked'),
                    OptionalID: $("#OptionalID").val(),
                };

                var DTO = JSON.stringify(OptionalDetailsViewModel);
                $.ajax({
                    url: urls["AddNewOptionalDetail"],
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: DTO,
                    success: function (data) {
                        $("#AddOptionalDetailsDiv").hide();
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        $('#AddOptionalDetailBtn').removeClass('BackColorRed');
                        jAlert("Data SuccessFully Saved:", "Successful");
                        ShowOptionalDetails($("#OptionalID").val());
                    }
                });
            }
        }
        else
            jAlert("Pax values can`t belong to the same range:", "Error!");
    }
}
$(document).on('click', '#OptionalMoreBtn', function () {
    TopScrollPossition = $("#OptionalGridDetailDiv").scrollTop();
    PageNumber = PageNumber + 1;
    LoadOptionalGrid()
});
$(document).on('click', '#OptionalSearchBtn', function () {
    IsSearchView = true;
    LoadOptionalGrid()
});
$(document).on('click', '#OptionalGridSaveBtn', function () {
    var $form = $('#LoadOptionalGridForm');
    if ($form.valid()) {
        if ($form[0].length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#OptionalGridSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    TopScrollPossition = $("#OptionalGridDetailDiv").scrollTop();
                    LoadOptionalGrid();
                }
            });
        }
        else
            jAlert("You have not data to save:", "Attention!");
    }
});
function ShowOptionalDetailPopUp(PopUpDiv) {
    if (PopUpDiv == "AddOptionalDiv")
    {
        $.colorbox({
            width: "800px",
            height: "300px",
            inline: true,
            href: "#" + PopUpDiv,
            onComplete: function () {
                $("#" + PopUpDiv).show();
            },
            onClosed: function () {
                $("#" + PopUpDiv).hide();
            }
        });
    }
    else
    {
        $.colorbox({
            width: "800px",
            height: "670px",
            inline: true,
            href: "#" + PopUpDiv,
            onComplete: function () {
                $("#" + PopUpDiv).show();
            },
            onClosed: function () {
                $("#" + PopUpDiv).hide();
            }
        });
    }
}
function isValidPaxFromTo()
{
    var isvalid = true
    $(".PaxFrom").each(function (index, elem) {
        var trparent = $(elem).parent();
        var tdparent = trparent.parent();
        var PaxTo = parseInt($(tdparent.find(".PaxTo")).val());
        var PaxFrom = parseInt(elem.value);
        if (PaxTo < PaxFrom)
        {
            isvalid = false;
            return;
        }
    });
    return isvalid;
}
function isValidPaxFromToRange() {
    var isvalid = true
    var PaxFromarr = [];
    var PaxToarr = [];
    $(".PaxFrom").each(function (index, elem) {
        var trparent = $(elem).parent();
        var tdparent = trparent.parent();
        var PaxTo = parseInt($(tdparent.find(".PaxTo")).val());
        var PaxFrom = parseInt(elem.value);
        PaxFromarr.push(PaxFrom);
        PaxToarr.push(PaxTo);
    });
    for (var index = 0 ; index < PaxFromarr.length ; ++index) {
        if (isvalid) {
            for (var index1 = index + 1 ; index1 < PaxFromarr.length ; ++index1) {
                if((PaxFromarr[index1] <= PaxToarr[index]) && (PaxFromarr[index1] >= PaxFromarr[index]) || (PaxToarr[index1] <= PaxToarr[index]) && (PaxToarr[index1] >= PaxFromarr[index]))
                {
                    isvalid = false;
                    break;
                }
            }
        }
        else
            break;
    }
    return isvalid;
}
$(document).on('click', '#OptionalDetailsSaveBtn', function () {
    if (isValidPaxFromTo()) {
        if (isValidPaxFromToRange()) {
            var $form = $('#LoadOptionalDetailsForm');
            if ($form.valid()) {
                OptionalValidationClientSideHide = false;
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: $form.serialize(),
                    beforeSend: function (xhr) {
                        xhr.overrideMimeType('text/plain; charset=x-user-defined');
                    },
                    success: function (data) {
                        if (data.indexOf("Error") != -1)
                            jAlert(data, "Error");
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        $('#OptionalDetailsSaveBtn').removeClass('BackColorRed');
                        if (OptionalIDGlobal == 0) {
                            $('#cboxClose').click();
                            LoadOptionalGrid();
                            ShowOptionalDetails(-1)
                        }
                        else {
                            jAlert("Data SuccessFully Saved:", "Successful");
                            ShowOptionalDetails(OptionalIDGlobal)
                        }
                    }
                });
            }
            else
                OptionalValidationClientSideHide = true;
        }
        else
            jAlert("Pax values can`t belong to the same range:", "Error!");
    }
    else
        jAlert("Pax to must be greater than pax from or equal:", "Error!");

});

function InitOptionalDetailsDataCalendars() {
   
    $(".OptionalDeteilsDataCalendar").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999999
            });
        }
    });
}
function InitOptionalDetailsDataCalendarsFromToDiv() {
    $(".OptionalDeteilsDataCalendarFromDiv").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999999,
            });
        },
        onClose: function (selectedDate) {
            $(".OptionalDeteilsDataCalendarToDiv").datepicker("option", "minDate", selectedDate);
        }
    });
    $(".OptionalDeteilsDataCalendarToDiv").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999999,
            });
        },
        onClose: function (selectedDate) {
            $(".OptionalDeteilsDataCalendarFromDiv").datepicker("option", "maxDate", selectedDate);
        }
    });
}
function InitOptionalDetailsDataCalendarsFromToDivForGrid() {
    $(".OptionalDeteilsDataCalendarFromDivInGrid").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999,
            });
        },
        onClose: function (selectedDate) {
            $(".OptionalDeteilsDataCalendarToDivInGrid").datepicker("option", "minDate", selectedDate);
        }
    });
    $(".OptionalDeteilsDataCalendarToDivInGrid").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999,
            });
        },
        onClose: function (selectedDate) {
            $(".OptionalDeteilsDataCalendarFromDivInGrid").datepicker("option", "maxDate", selectedDate);
        }
    });
}
function BindOptionalDetailsCurrencyDropGridDrop() {
    $(".CurrencyDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.CurrencyDrop', function () {
    $(this).next().prop("selectedIndex", $(this).prop("selectedIndex"));
});
$(document).on('change', '.AddCurrencyDrop', function () {
    AddCurrencyDropVal = this.options[this.selectedIndex].value;
});
function LoadOptionalGrid()
{
    var ManageOptionalsGridViewModel = {
        OptionalStartDateText: $("#OptionalStartDateText").val(),
        OptionalEndDateText: $("#OptionalEndDateText").val(),
        OptionalVendorNameText: $("#OptionalVendorNameText").val(),
        CitySearchText: $("#CitySearchText").val(),
        PageNum: parseInt(PageNumber),
        IsActiveSearch: $("#IsActiveSearch").val(),
        IsSearch: IsSearchView,
        TopScrollPossition: parseFloat(TopScrollPossition),
    };
    
    var DTO = JSON.stringify(ManageOptionalsGridViewModel);
    $.ajax({
        url: urls["OptionalLoadOptionalsGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#ManageOptionalGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            if ($("#TopScrollPossition").val() != "") {
                $("#OptionalGridDetailDiv").scrollTop(parseFloat($("#TopScrollPossition").val()));
            }
            InitOptionalDetailsDataCalendarsFromToDivForGrid();
        }
    });
}

// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (OptionalTimerId == null) {
        OptionalAutoComElem = $(this).attr('id');
        OptionalAutoComElemVal = $("#" + OptionalAutoComElem).val();
        OptionalTimerId = setInterval(function () {

            var keyword = $("#" + OptionalAutoComElem).val();
            if (keyword == OptionalAutoComElemVal) {
                var PropName = "";
                if (OptionalAutoComElem.indexOf("OptionalVendorNameText") != -1)
                    PropName = "OptionalVendorNameText";
                if (OptionalAutoComElem.indexOf("OptionalSelectedVendorName") != -1)
                    PropName = "OptionalSelectedVendorName";

                var position = $("#" + OptionalAutoComElem).offset();
                position.top = position.top + $("#" + OptionalAutoComElem).height() + 5;
                $.ajax({
                    url: urls["OptionalAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + OptionalAutoComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(OptionalTimerId);
                        OptionalTimerId = null;
                    }
                });
            }
            else
                OptionalAutoComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + OptionalAutoComElem).val(val);
    if (OptionalAutoComElem.indexOf("OptionalVendorNameText") != -1)
        $("#" + OptionalAutoComElem).next().val(key);
    if (OptionalAutoComElem.indexOf("OptionalSelectedVendorName") != -1)
        $("#" + OptionalAutoComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#OptionalDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddOptionalDiv").empty();
                $("#OptionalDetailsDiv").empty();
                LoadOptionalGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddOptionalDiv").empty();
        $("#OptionalDetailsDiv").empty();
        LoadOptionalGrid();
        originalClose();
    }
};

$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (OptionalValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});


